<template>
  <div class="profile-container">
    <el-card>
      <h2>个人信息</h2>
      <el-form :model="form" :rules="rules" ref="profileForm" label-width="100px">
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
              type="password"
              v-model="form.password"
              placeholder="请输入密码"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              type="password"
              v-model="form.confirmPassword"
              placeholder="请再次输入密码"
              show-password
          ></el-input>
        </el-form-item>
        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <!-- 电话号码 -->
        <el-form-item label="电话号码" prop="phone_number">
          <el-input v-model="form.phone_number" placeholder="请输入电话号码"></el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/userStore";
import { authService } from "../../axios/request.js";

// 表单数据
const form = reactive({
  nickname: "",
  password: "", // 新密码
  confirmPassword: "", // 确认密码（新增字段）
  sex: null,
  email: "",
  phone_number: "",
});

// 表单校验规则
const rules = reactive({
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      }, trigger: "blur" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入有效的邮箱地址", trigger: ["blur", "change"] },
  ],
  phone_number: [
    { required: true, message: "请输入电话号码", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
});

// 表单引用
const profileForm = ref(null);

// 提交表单
const submitForm = () => {
  profileForm.value.validate((valid) => {
    if (valid) {
      // 前端需传递confirmPassword给后端（后端仅校验，不存储）
      authService
          .post("/lyy/update_by_user", form)
          .then((response) => {
            if (response.data.result === 'success') {
              ElMessage.success(response.data.msg || "修改成功！");
              // 可选：更新成功后重新获取用户信息
              fetchCurrentUserInfo();
            } else {
              ElMessage.error(response.data.msg || "修改失败，请稍后重试");
            }
          })
          .catch(() => {
            ElMessage.error("服务器错误，请稍后重试");
          });
    }
  });
};

// 重置表单
const resetForm = () => {
  profileForm.value.resetFields();
};

const fetchCurrentUserInfo = async () => {
  try {
    console.log("11111111111111111111")
    const userStore = useUserStore();
    console.log("22222222222222222222", userStore.getToken)
    if (!userStore.getToken) {
      ElMessage.error("请先登录");
      // 假设 router 已经正确导入
      // router.push("/login");
      return;
    }

    const response = await authService.get("/lyy/get_current_user_info");

    // 检查响应状态码
    if (response.status === 200) {
      console.log("3333333333333333333")
      console.log(response.data)
      if (response.data.result === 'success') {
        console.log("4444444444444444444")
        const userInfo = response.data.data;
        form.nickname = userInfo.nickname;
        form.sex = userInfo.sex;
        form.email = userInfo.email;
        form.phone_number = userInfo.phone_number;
      } else {
        ElMessage.error(response.data.error || "获取用户信息失败，请稍后重试");
      }
    } else {
      ElMessage.error(`请求失败，状态码: ${response.status}`);
    }
  } catch (error) {
    if (error.response) {
      // 服务器返回了错误响应
      ElMessage.error(`请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data.error || '未知错误'}`);
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      ElMessage.error("没有收到服务器的响应，请检查网络连接");
    } else {
      // 其他错误
      ElMessage.error("发生未知错误:" + error.message);
    }
  }
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchCurrentUserInfo();
});
</script>

<style scoped>
.profile-container {
  max-width: 600px;
  margin: 20px auto;
}
</style>